# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Block users from mucking about with other users' changebranch areas.
"""


def RunHook(hi, logger):
  """Implements gvn.hooks.runner's RunHook interface

  Returns:
    -1: pass and bypass other hooks
    0: pass
    1: fail
    "string": fail and print string to the user
  """
  cbp = hi.project_config['change-branch-base'] + '/'
  prefix = hi.prefix_changed

  # Example with cbp == 'changes/':
  #   prefix                                    => (left, right)
  #   ----------------------------------------------------------------
  #   'trunk'                                   => ValueError
  #   'project/changes/foo'                     => ('project/', 'foo')
  #   'changes/basil'                           => ('', 'basil')
  #   'changes/basil/foo/trunk/doc/changes/foo' => ('', 'basil/foo/trunk/doc/changes/foo')
  try:
    (left, right) = prefix.split(cbp, 1)
  except ValueError:
    # Not a changebranch, so we don't care about it.
    return 0
  if left != '':
    # Not a changebranch, so we don't care about it.
    return 0

  # Got a changebranch, and the owner is everything in right before the /
  cb_area_owner = right.split('/')[0]
  if cb_area_owner != hi.author:
    return "%s cannot commit to %s's changebranch area" % (hi.author,
                                                           cb_area_owner)
  return 0
